package com.gxuwz.stats.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.service.FileParser;
import com.gxuwz.stats.service.FileParserFactory;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private FileParserFactory fileParserFactory;

    /**
     * 获取用户列表
     * @param params 请求参数
     * @param currentPage 当前页码
     * @param pageSize    每页大小
     * @return
     */
    @GetMapping("/userList")
    public ResponseEntity<Map<String, Object>> userList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<User> page = new Page<>(currentPage, pageSize);
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();

            // 模糊查询条件
            if (params.containsKey("userKeyword") && !params.get("userKeyword").isEmpty()) {
                String keyword = "%" + params.get("userKeyword") + "%";
                queryWrapper.and(wrapper -> wrapper
                        .like("username", keyword)
                        .or().like("role", keyword)
                        .or().like("degree", keyword)
                        .or().like("position", keyword)
                        .or().like("post", keyword)
                        .or().like("department", keyword));
            }

            // 调用 service 层的分页查询方法
            IPage<User> resultPage = userService.page(page, queryWrapper);

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords()); // 当前页数据
            response.put("total", resultPage.getTotal()); // 总记录数
            response.put("currentPage", resultPage.getCurrent()); // 当前页码
            response.put("pageSize", resultPage.getSize()); // 每页大小
            response.put("totalPages", resultPage.getPages()); // 总页数

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 导入用户表格数据
     * @param file
     * @param type 导入类型
     * @param updateSupport
     * @return
     */
//    @PostMapping("/importData")
//    public ResponseEntity<Map<String, Object>> importData(
//            @RequestParam("file") MultipartFile file,
//            @RequestParam("type") String type,
//            @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) {
//        try {
//            System.out.println("用户导入类型=" + type);
//
////            FileParser parser = fileParserFactory.getParser("excel");
//            // 传递 type 给 parser
////            if (parser instanceof com.gxuwz.stats.service.impl.ExcelParser) {
////                ((com.gxuwz.stats.service.impl.ExcelParser) parser).parse(file, type, null, null, null);
////                Map<String, Object> response = new HashMap<>();
////                response.put("code", 200);
////                response.put("message", "导入成功！");
////                return ResponseEntity.ok(response);
////            } else {
////                parser.parse(file); // 兼容其他类型
////            }
//            Map<String, Object> response = new HashMap<>();
//            response.put("code", 200);
//            response.put("message", "导入成功");
//            return ResponseEntity.ok(response);
//        } catch (Exception e) {
//            Map<String, Object> errorResponse = new HashMap<>();
//            errorResponse.put("code", 400);
//            errorResponse.put("message", "导入失败: " + e.getMessage());
//            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
//        }
//    }

    /**
     * 新增用户
     */
    @PostMapping("/addUser")
    public ResponseEntity<Map<String, Object>> addUser(@RequestBody User user) {
        System.out.println("user===" + user);
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            user.setPassword(new BCryptPasswordEncoder().encode("wzxy@123456"));
        }
        // 自动生成以1开头的五位数userId
//        user.setUserId(generateUniqueUserId());
        user.setFirstLogin(true);
        userService.save(user);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "新增成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/deleteUser")
    public ResponseEntity<Map<String, Object>> deleteUser(@RequestBody List<Long> userIds) {
        System.out.println("删除：" + userIds);
        userService.removeByIds(userIds);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 修改用户
     */
    @PutMapping("/editUser")
    public ResponseEntity<Map<String, Object>> editUser(@RequestBody User user) {
        System.out.println("user::" + user);
        userService.updateById(user);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 重置用户密码
     */
    @PostMapping("/resetPassword")
    public ResponseEntity<Map<String, Object>> resetPassword(@RequestBody Map<String, Object> requestBody) {
        try {
            Integer userId = Integer.valueOf(requestBody.get("userId").toString());
            String newPassword = generateRandomPassword();
            
            // 加密新密码
            String encodedPassword = new BCryptPasswordEncoder().encode(newPassword);
            
            // 更新用户密码
            User user = new User();
            user.setId(userId);
            user.setPassword(encodedPassword);
            userService.updateById(user);
            Map<String, String> data = new HashMap<>();
            data.put("newPassword", newPassword);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "密码重置成功");
            response.put("data", data);

//            response.put("data", Map.of("newPassword", newPassword));
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "密码重置失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 生成9位随机密码（包含大小写字母和数字）
     */
    private String generateRandomPassword() {
        String upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String lowerCase = "abcdefghijklmnopqrstuvwxyz";
        String numbers = "0123456789";
        String allChars = upperCase + lowerCase + numbers;
        
        StringBuilder password = new StringBuilder();
        Random random = new Random();
        
        // 确保至少包含一个大写字母、一个小写字母和一个数字
        password.append(upperCase.charAt(random.nextInt(upperCase.length())));
        password.append(lowerCase.charAt(random.nextInt(lowerCase.length())));
        password.append(numbers.charAt(random.nextInt(numbers.length())));
        
        // 剩余6位随机生成
        for (int i = 0; i < 6; i++) {
            password.append(allChars.charAt(random.nextInt(allChars.length())));
        }
        
        // 打乱密码顺序
        char[] passwordArray = password.toString().toCharArray();
        for (int i = passwordArray.length - 1; i > 0; i--) {
            int j = random.nextInt(i + 1);
            char temp = passwordArray[i];
            passwordArray[i] = passwordArray[j];
            passwordArray[j] = temp;
        }
        
        return new String(passwordArray);
    }

    // 生成唯一的以1开头的五位数userId
    private String generateUniqueUserId() {
        Random random = new Random();
        int maxAttempts = 10; // 最大尝试次数

        for (int i = 0; i < maxAttempts; i++) {
            // 生成10000-19999之间的随机数
            String userId = String.valueOf(10000 + random.nextInt(90000));

            // 检查唯一性（假设userService有此方法）
            if (!userService.existsByUserId(String.valueOf(userId))) {
                return userId;
            }
        }

        // 如果尝试多次仍无法生成唯一ID，抛出异常或使用其他策略
        throw new RuntimeException("生成唯一用户ID失败，请稍后重试");
    }
}

